<template>
    <div class="header-container">
        <!-- 显示用户头像或登录按钮 -->
        <el-dropdown size="medium" style="line-height: 60px;">
            <!--            判断是否登录-->
            <el-if v-if="isLoggedin">
                <span class="el-dropdown-link" style="cursor: pointer">
                    <span v-text="user.userName"></span>
                    <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>
                        <div style="width: 50px; text-align: center;" @click="logout">退出</div>
                    </el-dropdown-item>
                </el-dropdown-menu>
            </el-if>
            <el-else v-else>
                <el-button type="text" @click="toLoginDialog">去登录</el-button>
            </el-else>
        </el-dropdown>

        <!-- 登录提示 -->
        <el-dialog v-if="!isLoggedin" title="请先登录" :visible.sync="showLoginTip" :append-to-body="true">
            <div style="text-align:center;font-size:16px;color:#666;">您需要登录才能完整体验</div>
            <div style="text-align:center;margin-top:20px;">
                <el-button type="primary" size="medium" @click="toLoginDialog">立即登录</el-button>
            </div>
        </el-dialog>

        <!--        注册登录弹窗-->
        <el-dialog :title="dialogTitle" :visible.sync="loginDialogVisible" width="400px" :append-to-body="true" center>
            <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" size="big">
                <el-form-item prop="userAccount">
                    <el-input v-model="loginForm.userAccount" placeholder="请输入账号" prefix-icon="el-icon-user"></el-input>
                </el-form-item>
                <el-form-item prop="userPassword">
                    <el-input type="password" v-model="loginForm.userPassword" placeholder="请输入密码"
                              prefix-icon="el-icon-lock"></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="login(loginForm)">登录</el-button>
                    <el-button type="text" @click="shiftDialog('register')">去注册</el-button>
                    </span>
        </el-dialog>
        <el-dialog :title="dialogTitle" :visible.sync="registerDialogVisible" width="400px" :append-to-body="true"
                   center>
            <el-form ref="registerForm" :model="registerForm" :rules="registerRules" size="medium">
                <el-form-item prop="userName">
                    <el-input v-model="registerForm.userName" placeholder="请输入昵称"
                              prefix-icon="el-icon-user-solid"></el-input>
                </el-form-item>
                <el-form-item prop="userAccount">
                    <el-input v-model="registerForm.userAccount" placeholder="请输入账号"
                              prefix-icon="el-icon-user"></el-input>
                </el-form-item>
                <el-form-item prop="userPassword">
                    <el-input type="password" v-model="registerForm.userPassword" placeholder="请输入密码"
                              prefix-icon="el-icon-lock"></el-input>
                </el-form-item>
                <el-form-item prop="checkPassword">
                    <el-input type="password" v-model="registerForm.checkPassword" placeholder="再次确认密码"
                              prefix-icon="el-icon-lock"></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="register(registerForm)">注册</el-button>
                    <el-button type="warning" @click="resetRegisterForm">重置</el-button>
                    <el-button type="text" @click="shiftDialog('login')">去登录</el-button>
                </span>
        </el-dialog>
    </div>
</template>

<script>
    import request from "@/utils/request";
    import Cookies from 'js-cookie'

    export default {
        data() {
            return {
                // 是否登录
                isLoggedin: false,
                user: Cookies.get('user') ? JSON.parse(Cookies.get('user')) : {},
                // 提示登录
                showLoginTip: true,
                // 登录弹窗
                loginDialogVisible: false,
                registerDialogVisible: false,
                dialogType: 'register',
                dialogTitle: '用户登录',
                loginForm: {
                    userAccount: '',
                    userPassword: ''
                },
                loginRules: {
                    userAccount: [{required: true, message: '请输入账号', trigger: 'blur'}],
                    userPassword: [{required: true, message: '请输入密码', trigger: 'blur'}]
                },
                registerForm: {
                    userName: '',
                    userAccount: '',
                    userPassword: '',
                    checkPassword: '',
                },
                registerRules: {
                    userName: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 4, max: 9, message: '长度在4-9个字符', trigger: 'blur'}
                    ],
                    userAccount: [
                        {required: true, message: '请输入用户账号', trigger: 'blur'},
                        {min: 4, max: 9, message: '长度在4-9个字符', trigger: 'blur'},
                        {validator: this.validateUserAccount, trigger: 'blur'}
                    ],
                    userPassword: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 4, max: 9, message: '长度在6-12个字符', trigger: 'blur'}
                    ],
                    checkPassword: [
                        {required: true, message: '请再次输入密码', trigger: 'blur'},
                        {validator: this.validateConfirmPassword, trigger: 'blur'}
                    ]
                }
            };
        },
        mounted() {
            if (Cookies.get('user')) {
                console.log(this.user)
                console.log('已登录')
                this.isLoggedin = true;
            } else {
                this.isLoggedin = false;
                console.log('未登录')

            }

        },
        methods: {
            shiftDialog(type) {
                if (type === 'login') {
                    this.registerDialogVisible = false
                    this.loginDialogVisible = true
                    this.dialogTitle = '用户登录'
                } else if (type === 'register') {
                    this.loginDialogVisible = false
                    this.registerDialogVisible = true
                    this.dialogTitle = '用户注册'
                }
            },

            // 去登录
            toLoginDialog() {
                this.showLoginTip = false
                this.loginDialogVisible = true
            },
            // 登录
            login(loginform) {
                this.$refs.loginForm.validate((valid) => {
                    if (valid) {
                        request.post('/user/login', loginform).then(res => {
                            if (res.code === 200) {
                                if (res.data !== null) {
                                    Cookies.set('user', JSON.stringify(res.data))
                                }
                                this.isLoggedin = true
                                this.loginDialogVisible = false
                                this.$message({message: "登录成功", type: "success"})
                            } else {
                                this.$message({message: "登录失败", type: "error"})
                            }
                        })
                    } else {
                        // 验证不通过，不执行登录操作
                        return false;
                    }
                });
            },
            // 退出登录
            logout() {
                request.post('/user/logout').then(res=>{
                    console.log(res)
                })
                Cookies.remove('user')
                this.isLoggedin = false
                console.log('退出登录');
                this.$message({message: "已退出登录", type: "success"})
            },
            // 注册
            register(registerForm) {
                this.$refs.registerForm.validate(valid => {
                    // 验证表单填写正确
                    if (valid) {
                        request.post('/user/register', registerForm).then(res => {
                            if (res.code === 200) {
                                this.shiftDialog('login')
                                this.$message({message: '注册成功', type: 'success'})
                            } else {
                                this.$message({message: '注册失败', type: "error"})
                            }
                        })
                    } else {
                        this.$message({
                            message: '请填写正确的信息',
                            type: "error"
                        })
                    }
                });
            },
            // 重置表单
            resetRegisterForm() {
                this.$refs.registerForm.resetFields();
            },
            clearAllCallbacks() {
                this.$refs.loginForm.clearValidate();
                this.$refs.registerForm.clearValidate();
            },
            // 验证确认密码是否和密码一致
            validateConfirmPassword(rule, value, callback) {
                if (value !== this.registerForm.userPassword) {
                    callback(new Error('两次输入的密码不一致'));
                } else {
                    callback();
                }
            },
            // 验证账号是否重复
            validateUserAccount(rule, value, callback) {
                if (value != null) {
                    request.post("user/preRegister/" + value).then(res => {
                        if (res.code == "1") {
                            callback(new Error('账号已存在，换一个吧'));
                        } else {
                            callback();
                        }
                    })
                }
            }
        }
    }
</script>

<style scoped>
    .header-container {
        display: flex;
        /*justify-content: flex-end;*/
        justify-content: center;
        align-items: center;
    }

    .user-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        cursor: pointer;
    }
</style>